import { PrismaClient, RechargeStatus, PaymentChannel } from '@prisma/client';
import { paymentService } from './paymentService';
import { isTopPayConfigured, createTopPayService } from './topPayService';
import { isPay668Configured, createPay668Service } from './pay668Service';
import { isLspPayConfigured, createLspPayService } from './lspPayService';
import { isHuifengConfigured, createHuifengPayService } from './huifengPayService';
import { isNaskiConfigured, createNaskiPayService } from './naskiPayService';
import { cardSellService } from './cardSellService';
import { telegramService, type CardSellNotificationData } from './telegramService';
import { paymentMonitorService } from './paymentMonitorService';
import { Logger, AppError, ErrorCode, handleError } from '../utils/logger';

const prisma = new PrismaClient();

export interface CreateRechargeOrderInput {
  userId: number; // 恢复必填
  amount: number;
  paymentChannel?: PaymentChannel; // 支付渠道（可选，不指定时自动选择）
  paymentMethod: 'BankTransfer' | 'qrPay';
  createdByUserId: number | null; // 创建订单的用户ID（管理员创建时有值，用户自助充值时为null）
  createdByName: string; // 开单客服名称（用户输入）
  transAccNo: string; // 银行卡号（所有支付方式都必填）
  paymentName: string; // 付款人真实名称（必填）
  bankCode: string; // 银行编码（所有支付方式都必填）
  customerEmail?: string; // 客户邮箱（可选）
  customerPhone?: string; // 客户手机号（可选）
  extendParam?: string; // 透传参数（上传的内容会原路返回）
  useAutoSelection?: boolean; // 是否使用自动渠道选择（默认true）
}

export interface QueryRechargeOrdersInput {
  orderId?: string;
  userId?: number;
  status?: RechargeStatus;
  createdByUserId?: number;
  createdByName?: string; // 开单客服名称搜索
  page: number;
  limit: number;
}

export class RechargeService {
  private topPayService = createTopPayService();
  private pay668Service = createPay668Service();
  private lspPayService = createLspPayService();
  private huifengPayService = createHuifengPayService();
  private naskiPayService = createNaskiPayService();

  /**
   * 获取回调地址
   */
  private getNotifyUrl(channel: PaymentChannel): string {
    switch (channel) {
      case PaymentChannel.TOPPAY:
        return process.env.TOPPAY_NOTIFY_URL || '';
      case PaymentChannel.PAY668:
        return process.env.PAY668_NOTIFY_URL || '';
      case PaymentChannel.LSPPAY:
        return process.env.LSPPAY_NOTIFY_URL || '';
      case PaymentChannel.HUIFENG:
        return process.env.HUIFENG_NOTIFY_URL || '';
      default:
        return '';
    }
  }

  /**
   * 创建充值订单（支持智能重试）
   */
  async createRechargeOrder(input: CreateRechargeOrderInput) {
    const retryEnabled = process.env.PAYMENT_RETRY_ENABLED === 'true';
    const maxRetries = retryEnabled ? parseInt(process.env.PAYMENT_MAX_RETRIES || '2') : 0;
    const retryDelayMs = parseInt(process.env.PAYMENT_RETRY_DELAY_MS || '1000');
    const excludedChannels: PaymentChannel[] = [];
    const retryHistory: Array<{
      attempt: number;
      channel: PaymentChannel;
      orderId: string;
      success: boolean;
      errorCode?: string;
      errorMessage?: string;
      duration: number;
    }> = [];

    Logger.info(`开始创建充值订单（${retryEnabled ? '智能重试模式' : '单次尝试模式'}）`, {
      userId: input.userId,
      amount: input.amount,
      paymentChannel: input.paymentChannel,
      retryEnabled,
      maxRetries,
      useAutoSelection: input.useAutoSelection !== false
    });

    for (let attempt = 1; attempt <= maxRetries + 1; attempt++) {
      const attemptStartTime = Date.now();
      let selectedChannel: PaymentChannel;
      let channelSelectionReason = '手动指定渠道';
      let orderId: string;

      try {
        // 首先检查是否有任何可用渠道
        const allAvailableChannels = paymentService.getAvailableChannels();
        if (allAvailableChannels.length === 0) {
          Logger.error('没有任何可用的支付渠道', new Error('No available channels configured'), {
            attempt,
            amount: input.amount,
            allAvailableChannels,
            excludedChannels
          });
          
          throw new AppError(
            '网络繁忙，请稍后重试',
            ErrorCode.PAYMENT_CHANNEL_ERROR,
            {
              retryHistory,
              excludedChannels: [],
              finalAttempt: attempt,
              reason: '没有可用的支付渠道'
            }
          );
        }

        // 渠道选择逻辑
        if (!input.paymentChannel || input.useAutoSelection !== false) {
          const selection = paymentService.selectOptimalChannel(input.amount, excludedChannels);
          
          if (selection.selectedChannel) {
            selectedChannel = selection.selectedChannel;
            channelSelectionReason = `${selection.reason} (尝试 ${attempt}/${maxRetries + 1})`;
            
            Logger.info(`第${attempt}次尝试 - 自动选择渠道成功`, {
              attempt,
              amount: input.amount,
              selectedChannel,
              reason: selection.reason,
              excludedChannels,
              availableChannels: selection.availableChannels,
              totalWeight: selection.totalWeight
            });
          } else {
            // 自动选择失败，检查是否还有可用渠道
            if (input.paymentChannel && !excludedChannels.includes(input.paymentChannel)) {
              selectedChannel = input.paymentChannel;
              channelSelectionReason = `自动选择失败，使用手动指定渠道 (尝试 ${attempt}/${maxRetries + 1})`;
            } else {
              // 获取剩余可用渠道，排除已失败的
              const remainingChannels = allAvailableChannels.filter(ch => !excludedChannels.includes(ch));
              
              if (remainingChannels.length > 0) {
                selectedChannel = remainingChannels[0];
                channelSelectionReason = `自动选择失败，使用默认渠道 (尝试 ${attempt}/${maxRetries + 1})`;
              } else {
                // 所有渠道都已尝试失败
                Logger.error('所有支付渠道都已尝试失败', new Error('All available channels failed'), {
                  attempt,
                  excludedChannels,
                  allAvailableChannels,
                  retryHistory
                });
                
                throw new AppError(
                  '网络繁忙，请稍后重试',
                  ErrorCode.PAYMENT_CHANNEL_ERROR,
                  {
                    retryHistory,
                    excludedChannels,
                    finalAttempt: attempt
                  }
                );
              }
            }
            
            Logger.warn(`第${attempt}次尝试 - 自动渠道选择失败`, {
              attempt,
              amount: input.amount,
              reason: selection.reason,
              fallbackChannel: selectedChannel,
              fallbackReason: channelSelectionReason,
              excludedChannels
            });
          }
        } else {
          // 手动指定渠道，检查是否在排除列表中
          if (excludedChannels.includes(input.paymentChannel)) {
            throw new AppError(
              '指定的支付渠道暂时不可用，请稍后重试',
              ErrorCode.PAYMENT_CHANNEL_ERROR,
              { channel: input.paymentChannel, excludedChannels }
            );
          }
          selectedChannel = input.paymentChannel;
          channelSelectionReason = `手动指定渠道 (尝试 ${attempt}/${maxRetries + 1})`;
        }

        orderId = paymentService.generateOrderId(selectedChannel);

        Logger.info(`第${attempt}次尝试 - 开始创建充值订单`, {
          attempt,
          orderId,
          userId: input.userId,
          amount: input.amount,
          selectedChannel,
          paymentMethod: input.paymentMethod,
          createdByUserId: input.createdByUserId
        });

        // 检查支付渠道配置
        if (!paymentService.isChannelConfigured(selectedChannel)) {
          const configError = new AppError(
            `支付渠道 ${selectedChannel} 未配置，请联系管理员配置支付参数`,
            ErrorCode.PAYMENT_CONFIG_ERROR,
            { orderId, channel: selectedChannel }
          );
          
          // 配置错误不重试，直接抛出
          Logger.error(`第${attempt}次尝试 - 渠道配置错误`, configError, {
            attempt,
            orderId,
            channel: selectedChannel
          });
          throw configError;
        }

        // 创建数据库记录
        const rechargeRecord = await prisma.rechargeRecord.create({
          data: {
            userId: input.userId,
            amount: input.amount,
            paymentChannel: selectedChannel,
            paymentMethod: input.paymentMethod,
            orderId,
            createdByUserId: input.createdByUserId,
            createdByName: input.createdByName,
            status: RechargeStatus.PENDING,
            notifyUrl: this.getNotifyUrl(selectedChannel),
            transAccNo: input.transAccNo,
            paymentName: input.paymentName,
            bankCode: input.bankCode,
            extendParam: `${input.extendParam || ''} | 渠道选择: ${channelSelectionReason} | 重试历史: ${JSON.stringify(retryHistory)}`,
          },
          include: {
            createdByUser: {
              select: {
                id: true,
                username: true,
                email: true,
              },
            },
          },
        });

        // 调用支付API
        const paymentResponse = await paymentService.createRechargeOrder({
          userId: input.userId,
          amount: input.amount,
          paymentChannel: selectedChannel,
          paymentMethod: input.paymentMethod,
          orderId,
          transAccNo: input.transAccNo,
          paymentName: input.paymentName,
          bankCode: input.bankCode,
          customerEmail: input.customerEmail,
          customerPhone: input.customerPhone,
          extendParam: input.extendParam,
        });

        const duration = Date.now() - attemptStartTime;

        // 检查支付渠道是否成功创建订单
        if (!paymentResponse.success) {
          // 记录失败尝试
          retryHistory.push({
            attempt,
            channel: selectedChannel,
            orderId,
            success: false,
            errorCode: paymentResponse.errorCode,
            errorMessage: paymentResponse.errorMessage,
            duration
          });

          // 支付渠道创建失败，删除已创建的数据库记录
          await prisma.rechargeRecord.delete({
            where: { id: rechargeRecord.id }
          });

          Logger.error(`第${attempt}次尝试 - 支付渠道创建订单失败`, new Error(paymentResponse.errorMessage || '未知错误'), {
            attempt,
            orderId,
            channel: selectedChannel,
            errorCode: paymentResponse.errorCode,
            errorMessage: paymentResponse.errorMessage,
            duration,
            retryHistory
          });

          // 将失败的渠道加入排除列表
          if (!excludedChannels.includes(selectedChannel)) {
            excludedChannels.push(selectedChannel);
          }

          // 如果这是最后一次尝试，抛出错误
          if (attempt >= maxRetries + 1) {
            throw new AppError(
              '网络繁忙，请稍后重试',
              ErrorCode.PAYMENT_API_ERROR,
              {
                retryHistory,
                excludedChannels,
                finalAttempt: attempt,
                lastError: paymentResponse.errorMessage
              }
            );
          }

          // 等待一段时间后重试
          if (retryDelayMs > 0) {
            Logger.info(`第${attempt}次尝试失败，等待 ${retryDelayMs}ms 后重试`, {
              attempt,
              nextAttempt: attempt + 1,
              delayMs: retryDelayMs
            });
            await new Promise(resolve => setTimeout(resolve, retryDelayMs));
          }

          continue; // 继续下一次重试
        }

        // 成功！更新记录并返回
        const updatedRecord = await prisma.rechargeRecord.update({
          where: { id: rechargeRecord.id },
          data: {
            platOrderNum: paymentResponse.platOrderNum,
            payFee: null, // 手续费暂时设为null，后续通过通知更新
            paymentResponse: JSON.stringify(paymentResponse.rawResponse),
          },
          include: {
            createdByUser: {
              select: {
                id: true,
                username: true,
                email: true,
              },
            },
          },
        });

        // 记录成功尝试
        retryHistory.push({
          attempt,
          channel: selectedChannel,
          orderId,
          success: true,
          duration
        });

        Logger.orderCreated(orderId, {
          userId: input.userId,
          amount: input.amount,
          paymentChannel: selectedChannel,
          platOrderNum: paymentResponse.platOrderNum,
          createdByUserId: input.createdByUserId,
          attempt,
          retryHistory,
          totalDuration: Date.now() - (attemptStartTime - duration)
        });

        // 启动支付状态监控服务
        Logger.info(`启动订单 ${orderId} 支付状态监控`, {
          orderId,
          paymentChannel: selectedChannel,
          userId: input.userId,
          amount: input.amount
        });

        paymentMonitorService.startMonitoring(orderId, selectedChannel);

        return {
          rechargeRecord: updatedRecord,
          paymentResponse,
          selectedChannel,
          retryHistory
        };

      } catch (error) {
        const duration = Date.now() - attemptStartTime;
        
        // 如果是配置错误或其他致命错误，不重试
        if (error instanceof AppError && 
            (error.code === ErrorCode.PAYMENT_CONFIG_ERROR || error.code === ErrorCode.PAYMENT_CHANNEL_ERROR)) {
          Logger.error('致命错误，停止重试', error, {
            attempt,
            userId: input.userId,
            amount: input.amount,
            retryHistory
          });
          throw error;
        }

        // 记录失败尝试
        retryHistory.push({
          attempt,
          channel: selectedChannel!,
          orderId: orderId!,
          success: false,
          errorMessage: error instanceof Error ? error.message : '未知错误',
          duration
        });

        Logger.error(`第${attempt}次尝试 - 创建充值订单异常`, error, {
          attempt,
          orderId: orderId!,
          userId: input.userId,
          amount: input.amount,
          duration,
          retryHistory
        });

        // 如果这是最后一次尝试，抛出错误
        if (attempt >= maxRetries + 1) {
          throw new AppError(
            '网络繁忙，请稍后重试',
            ErrorCode.PAYMENT_API_ERROR,
            {
              retryHistory,
              finalAttempt: attempt,
              originalError: error instanceof Error ? error.message : '未知错误'
            }
          );
        }

        // 将出错的渠道加入排除列表
        if (selectedChannel! && !excludedChannels.includes(selectedChannel!)) {
          excludedChannels.push(selectedChannel!);
        }

        // 等待后重试
        if (retryDelayMs > 0) {
          await new Promise(resolve => setTimeout(resolve, retryDelayMs));
        }
      }
    }

    // 理论上不会执行到这里
    throw new AppError('重试机制异常结束', ErrorCode.INTERNAL_ERROR);
  }

  /**
   * 查询充值订单
   */
  async queryRechargeOrders(input: QueryRechargeOrdersInput) {
    try {
      const where: any = {};

      if (input.orderId) {
        where.orderId = input.orderId;
      }
      if (input.userId) {
        where.userId = input.userId;
      }
      if (input.status) {
        where.status = input.status;
      }
      if (input.createdByUserId) {
        where.createdByUserId = input.createdByUserId;
      }
      if (input.createdByName) {
        where.createdByName = {
          contains: input.createdByName,
          mode: 'insensitive'
        };
      }

      const [records, total] = await Promise.all([
        prisma.rechargeRecord.findMany({
          where,
          include: {
            createdByUser: {
              select: {
                id: true,
                username: true,
                email: true,
              },
            },
          },
          orderBy: {
            createdAt: 'desc',
          },
          skip: (input.page - 1) * input.limit,
          take: input.limit,
        }),
        prisma.rechargeRecord.count({ where }),
      ]);

      return {
        records,
        total,
        page: input.page,
        limit: input.limit,
        totalPages: Math.ceil(total / input.limit),
      };
    } catch (error) {
      throw new Error(`查询充值订单失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 根据订单号获取充值记录
   */
  async getRechargeRecordByOrderId(orderId: string) {
    try {
      return await prisma.rechargeRecord.findUnique({
        where: { orderId },
        include: {
          createdByUser: {
            select: {
              id: true,
              username: true,
              email: true,
            },
          },
        },
      });
    } catch (error) {
      throw new Error(`获取充值记录失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 查询TopPay订单状态
   */
  async queryTopPayOrderStatus(orderId: string, platOrderNum?: string) {
    try {
      // 检查TopPay配置
      if (!isTopPayConfigured()) {
        throw new Error('TopPay未配置，无法查询订单状态');
      }

      // 调用TopPay查询API
      const queryResponse = await this.topPayService.queryOrder(orderId, platOrderNum);

      // 如果查询成功且有数据，更新本地订单状态
      if (queryResponse.success && queryResponse.data) {
        const localRecord = await this.getRechargeRecordByOrderId(orderId);
        if (localRecord) {
          // 根据TopPay返回的状态更新本地状态
          let newStatus: RechargeStatus = localRecord.status;

          if (typeof queryResponse.data.status === 'string') {
            // 代收订单状态
            switch (queryResponse.data.status) {
              case 'SUCCESS':
                newStatus = RechargeStatus.COMPLETED;
                break;
              case 'PAY_ERROR':
                newStatus = RechargeStatus.FAILED;
                break;
              case 'PAY_CANCEL':
                newStatus = RechargeStatus.CANCELLED;
                break;
              case 'NO_PAY':
              case 'INIT_ORDER':
                newStatus = RechargeStatus.PENDING;
                break;
            }
          }

          // 如果状态有变化，更新数据库
          if (newStatus !== localRecord.status) {
            await prisma.rechargeRecord.update({
              where: { id: localRecord.id },
              data: {
                status: newStatus,
                payFee: queryResponse.data.fee ? parseFloat(queryResponse.data.fee) : localRecord.payFee,
              },
            });
          }
        }
      }

      return queryResponse;
    } catch (error) {
      throw new Error(`查询TopPay订单状态失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 查询668Pay订单状态
   */
  async queryPay668OrderStatus(orderId: string, platOrderNum?: string) {
    try {
      // 检查668Pay配置
      if (!isPay668Configured()) {
        throw new Error('668Pay未配置，无法查询订单状态');
      }

      // 调用668Pay查询API
      const queryResponse = await this.pay668Service.queryOrderStatus({
        mchOrderNo: orderId,
        payOrderId: platOrderNum
      });

      // 如果查询成功且有数据，更新本地订单状态
      if (queryResponse.code === 0 && queryResponse.data) {
        const localRecord = await this.getRechargeRecordByOrderId(orderId);
        if (localRecord) {
          // 根据668Pay返回的状态更新本地状态
          let newStatus: RechargeStatus = localRecord.status;

          // 668Pay订单状态：1: 支付中, 2: 支付成功, 3: 支付失败, 6: 订单关闭, 7: 订单待结算
          switch (queryResponse.data.state) {
            case 2: // 支付成功
            case 7: // 订单待结算
              newStatus = RechargeStatus.COMPLETED;
              break;
            case 3: // 支付失败
              newStatus = RechargeStatus.FAILED;
              break;
            case 6: // 订单关闭
              newStatus = RechargeStatus.CANCELLED;
              break;
            case 1: // 支付中
              newStatus = RechargeStatus.PENDING;
              break;
          }

          // 如果状态有变化，更新数据库
          if (newStatus !== localRecord.status) {
            await prisma.rechargeRecord.update({
              where: { id: localRecord.id },
              data: {
                status: newStatus,
                // 668Pay返回的金额是分，需要转换为元
                amount: queryResponse.data.amount ? queryResponse.data.amount / 100 : localRecord.amount,
                platOrderNum: queryResponse.data.payOrderId || localRecord.platOrderNum,
              },
            });
          }
        }
      }

      return queryResponse;
    } catch (error) {
      throw new Error(`查询668Pay订单状态失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 查询LSPPAY订单状态
   */
  async queryLspPayOrderStatus(orderId: string, platOrderNum?: string) {
    try {
      // 检查LSPPAY配置
      if (!isLspPayConfigured()) {
        throw new Error('LSPPAY未配置，无法查询订单状态');
      }

      // 调用LSPPAY查询API
      const queryResponse = await this.lspPayService.queryOrder(orderId);

      // 如果查询成功且有数据，更新本地订单状态
      if (queryResponse.code === 0 && queryResponse.data) {
        const localRecord = await this.getRechargeRecordByOrderId(orderId);
        if (localRecord) {
          // 根据LSPPAY返回的状态更新本地状态
          let newStatus: RechargeStatus = localRecord.status;

          // LSPPAY订单状态：0: 订单生成, 1: 支付中, 2: 支付成功, 3: 支付失败, 4: 已撤销, 5: 已退款, 6: 订单关闭
          switch (queryResponse.data.state) {
            case 2: // 支付成功
              newStatus = RechargeStatus.COMPLETED;
              break;
            case 3: // 支付失败
              newStatus = RechargeStatus.FAILED;
              break;
            case 4: // 已撤销
            case 6: // 订单关闭
              newStatus = RechargeStatus.CANCELLED;
              break;
            case 0: // 订单生成
            case 1: // 支付中
              newStatus = RechargeStatus.PENDING;
              break;
          }

          // 如果状态有变化，更新数据库
          if (newStatus !== localRecord.status) {
            await prisma.rechargeRecord.update({
              where: { id: localRecord.id },
              data: {
                status: newStatus,
                // LSPPAY返回的金额是分，需要转换为元
                amount: queryResponse.data.amount ? queryResponse.data.amount / 100 : localRecord.amount,
                platOrderNum: queryResponse.data.payOrderId || localRecord.platOrderNum,
              },
            });
          }
        }
      }

      return queryResponse;
    } catch (error) {
      throw new Error(`查询LSPPAY订单状态失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 查询汇沣支付订单状态
   */
  async queryHuifengOrderStatus(orderId: string, platOrderNum?: string) {
    try {
      // 检查汇沣支付配置
      if (!this.huifengPayService) {
        throw new Error('汇沣支付未配置，无法查询订单状态');
      }

      // 调用汇沣支付查询API
      const queryResponse = await this.huifengPayService.queryOrder(platOrderNum || orderId, orderId);

      // 如果查询成功且有数据，更新本地订单状态
      if (queryResponse.code === 0 && queryResponse.data) {
        const localRecord = await this.getRechargeRecordByOrderId(orderId);
        if (localRecord) {
          // 根据汇沣支付返回的状态更新本地状态
          let newStatus: RechargeStatus = localRecord.status;

          // 汇沣支付订单状态：200=成功, 999=失败, 666=超时
          switch (queryResponse.data.status) {
            case 200: // 支付成功
              newStatus = RechargeStatus.COMPLETED;
              break;
            case 999: // 支付失败
              newStatus = RechargeStatus.FAILED;
              break;
            case 666: // 超时
              newStatus = RechargeStatus.CANCELLED;
              break;
            default: // 其他状态保持待处理
              newStatus = RechargeStatus.PENDING;
              break;
          }

          // 如果状态有变化，更新数据库
          if (newStatus !== localRecord.status) {
            await prisma.rechargeRecord.update({
              where: { id: localRecord.id },
              data: {
                status: newStatus,
                amount: queryResponse.data.amount ? parseFloat(queryResponse.data.amount) : localRecord.amount,
                platOrderNum: queryResponse.data.order_num || localRecord.platOrderNum,
              },
            });
          }
        }
      }

      return queryResponse;
    } catch (error) {
      throw new Error(`查询汇沣支付订单状态失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 查询NASKI订单状态
   */
  async queryNaskiOrderStatus(orderId: string, platOrderNum?: string) {
    try {
      // 检查NASKI配置
      if (!this.naskiPayService) {
        throw new Error('NASKI支付未配置，无法查询订单状态');
      }

      // 调用NASKI查询API
      const queryResponse = await this.naskiPayService.queryOrder(orderId, platOrderNum);

      // 如果查询成功且有数据，更新本地订单状态
      if (queryResponse.code === 200 && queryResponse.data) {
        const localRecord = await this.getRechargeRecordByOrderId(orderId);
        if (localRecord) {
          // 根据NASKI返回的状态更新本地状态
          let newStatus: RechargeStatus = localRecord.status;

          // NASKI订单状态：5=成功, 4=关闭, 2=待支付, 3=失败
          switch (queryResponse.data.status) {
            case 5: // 支付成功
              newStatus = RechargeStatus.COMPLETED;
              break;
            case 3: // 支付失败
              newStatus = RechargeStatus.FAILED;
              break;
            case 4: // 订单关闭
              newStatus = RechargeStatus.CANCELLED;
              break;
            case 2: // 待支付
              newStatus = RechargeStatus.PENDING;
              break;
            default:
              newStatus = RechargeStatus.PENDING;
              break;
          }

          // 如果状态有变化，更新数据库
          if (newStatus !== localRecord.status) {
            await prisma.rechargeRecord.update({
              where: { id: localRecord.id },
              data: {
                status: newStatus,
                amount: queryResponse.data.payAmount ? parseFloat(queryResponse.data.payAmount) : localRecord.amount,
                platOrderNum: queryResponse.data.orderNo || localRecord.platOrderNum,
              },
            });
          }
        }
      }

      return queryResponse;
    } catch (error) {
      throw new Error(`查询NASKI订单状态失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 处理支付异步通知（通用方法）
   */
  async handlePaymentNotification(channel: PaymentChannel, data: any) {
    try {
      Logger.info('收到支付异步通知', { channel, orderId: data.orderNum || data.mchOrderNo });

      // 验证签名
      const isValidSignature = paymentService.verifyNotification(channel, data);
      if (!isValidSignature) {
        Logger.error('支付通知签名验证失败', new Error('Invalid signature'), { channel });
        throw new Error('签名验证失败');
      }

      // 解析通知数据
      const notification = paymentService.parseNotification(channel, data);
      if (!notification) {
        Logger.error('支付通知解析失败', new Error('Parse failed'), { channel });
        throw new Error('通知数据解析失败');
      }

      // 查找订单
      const rechargeRecord = await this.getRechargeRecordByOrderId(notification.orderId);
      if (!rechargeRecord) {
        Logger.error('订单不存在', new Error('Order not found'), { orderId: notification.orderId, channel });
        throw new Error('订单不存在');
      }

      // 🔥 添加已处理订单检查：如果订单已经是最终状态，直接返回成功
      if (rechargeRecord.status === RechargeStatus.COMPLETED ||
          rechargeRecord.status === RechargeStatus.FAILED ||
          rechargeRecord.status === RechargeStatus.CANCELLED) {
        Logger.info('订单已经是最终状态，跳过处理', {
          orderId: notification.orderId,
          currentStatus: rechargeRecord.status,
          notificationStatus: notification.status,
          channel,
          trigger: 'payment_callback'
        });
        return rechargeRecord; // 返回现有记录，不抛出错误
      }

      // 更新订单状态
      let status: RechargeStatus;
      switch (notification.status) {
        case 'SUCCESS':
          status = RechargeStatus.COMPLETED;
          break;
        case 'PAY_ERROR':
          status = RechargeStatus.FAILED;
          break;
        case 'PAY_CANCEL':
          status = RechargeStatus.CANCELLED;
          break;
        case 'NO_PAY':
        case 'INIT_ORDER':
          status = RechargeStatus.PENDING;
          break;
        default:
          Logger.warn('未知的订单状态', { status: notification.status, orderId: notification.orderId });
          status = RechargeStatus.PENDING;
      }

      // 更新数据库记录
      const updateData: any = {
        status,
        platOrderNum: notification.platOrderNum,
        paymentResponse: JSON.stringify(notification.rawData),
        updatedAt: new Date()
      };

      // 更新手续费信息
      if (notification.payFee) {
        updateData.payFee = parseFloat(notification.payFee);
      }

      const updatedRecord = await prisma.rechargeRecord.update({
        where: { id: rechargeRecord.id },
        data: updateData,
      });

      Logger.info('订单状态已更新', {
        orderId: notification.orderId,
        oldStatus: rechargeRecord.status,
        newStatus: status,
        channel,
        platOrderNum: notification.platOrderNum
      });

      // 如果订单完成，执行自动售卡和通知流程
      if (status === RechargeStatus.COMPLETED) {
        Logger.info('订单支付成功，开始执行售卡流程', {
          orderId: notification.orderId,
          amount: notification.amount,
          channel,
          trigger: 'payment_callback'
        });

        // 🔥 关键修复：添加自动售卡和通知流程
        try {
          // 停止该订单的轮询监控（如果存在）
          paymentMonitorService.stopMonitoring(notification.orderId);

          // 执行售卡和通知流程
          const cardSellResult = await this.executeCardSellAndNotify(notification.orderId);
          Logger.info('✅ 支付回调触发的自动发金币完成', {
            orderId: notification.orderId,
            sellCardSuccess: cardSellResult.sellCardSuccess,
            telegramSent: cardSellResult.telegramSent,
            message: cardSellResult.message,
            trigger: 'payment_callback'
          });
        } catch (error) {
          Logger.error('❌ 支付回调触发的自动发金币失败', error, {
            orderId: notification.orderId,
            trigger: 'payment_callback'
          });
          // 不抛出错误，避免影响回调确认
          // 轮询机制会作为备用方案继续工作
        }
      }

      return updatedRecord;
    } catch (error) {
      Logger.error('处理支付通知失败', error, { channel });
      throw new Error(`处理支付通知失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 处理TopPay异步通知（保持向后兼容）
   */
  async handleTopPayNotification(notification: any) {
    return this.handlePaymentNotification(PaymentChannel.TOPPAY, notification);
  }

  /**
   * 处理668Pay异步通知
   */
  async handlePay668Notification(notification: any) {
    return this.handlePaymentNotification(PaymentChannel.PAY668, notification);
  }

  /**
   * 原有的TopPay异步通知处理方法（已废弃，保持向后兼容）
   */
  async handleTopPayNotificationLegacy(notification: any) {
    try {
      console.log('收到TopPay异步通知:', JSON.stringify(notification, null, 2));

      // 检查TopPay配置
      if (!isTopPayConfigured()) {
        console.error('TopPay未配置，无法处理回调通知');
        throw new Error('TopPay未配置，无法处理回调通知');
      }

      // 验证签名
      const isValidSignature = this.topPayService.verifyNotification(notification);
      console.log('签名验证结果:', isValidSignature);

      if (!isValidSignature) {
        console.error('TopPay通知签名验证失败');
        throw new Error('签名验证失败');
      }

      // 查找订单
      const rechargeRecord = await this.getRechargeRecordByOrderId(notification.orderNum);
      if (!rechargeRecord) {
        console.error(`订单不存在: ${notification.orderNum}`);
        throw new Error('订单不存在');
      }

      console.log('找到订单记录:', {
        id: rechargeRecord.id,
        orderId: rechargeRecord.orderId,
        currentStatus: rechargeRecord.status,
        notificationStatus: notification.status
      });

      // 检查订单状态是否已经是最终状态
      if (rechargeRecord.status === RechargeStatus.COMPLETED ||
          rechargeRecord.status === RechargeStatus.FAILED ||
          rechargeRecord.status === RechargeStatus.CANCELLED) {
        console.log('订单已经是最终状态，跳过更新');
        return;
      }

      // 更新订单状态
      let status: RechargeStatus;
      switch (notification.status) {
        case 'SUCCESS':
          status = RechargeStatus.COMPLETED;
          break;
        case 'PAY_ERROR':
          status = RechargeStatus.FAILED;
          break;
        case 'PAY_CANCEL':
          status = RechargeStatus.CANCELLED;
          break;
        case 'NO_PAY':
        case 'INIT_ORDER':
          status = RechargeStatus.PENDING;
          break;
        default:
          console.warn(`未知的订单状态: ${notification.status}`);
          status = RechargeStatus.PENDING;
      }

      // 更新数据库记录
      const updateData: any = {
        status,
        platOrderNum: notification.platOrderNum,
        topPayResponse: JSON.stringify(notification),
        updatedAt: new Date()
      };

      // 更新手续费信息
      if (notification.payFee) {
        updateData.payFee = parseFloat(notification.payFee);
      }

      const updatedRecord = await prisma.rechargeRecord.update({
        where: { id: rechargeRecord.id },
        data: updateData,
      });

      console.log(`订单 ${notification.orderNum} 状态已更新为: ${status}`, {
        oldStatus: rechargeRecord.status,
        newStatus: status,
        payFee: notification.payFee,
        platOrderNum: notification.platOrderNum
      });

      // 如果订单完成，可以在这里添加后续处理逻辑
      if (status === RechargeStatus.COMPLETED) {
        console.log(`订单 ${notification.orderNum} 支付成功，金额: ${notification.payMoney}`);
        // 这里可以添加成功后的业务逻辑，比如发送通知等
      }

      return updatedRecord;
    } catch (error) {
      console.error('处理TopPay通知失败:', error);
      throw new Error(`处理TopPay通知失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 执行售卡并发送Telegram通知
   * 当充值成功后调用此方法进行自动售卡
   */
  async executeCardSellAndNotify(orderId: string): Promise<{
    success: boolean;
    sellCardSuccess: boolean;
    message: string;
    telegramSent: boolean;
  }> {
    try {
      Logger.info('开始执行售卡流程', { orderId });
      // 1. 获取充值记录
      const rechargeRecord = await this.getRechargeRecordByOrderId(orderId);
      if (!rechargeRecord) {
        throw new Error('充值记录不存在');
      }

      // 2. 检查是否已经处理过售卡
      if (rechargeRecord.sellCardStatus) {
        Logger.info('订单已处理过售卡', {
          orderId,
          sellCardStatus: rechargeRecord.sellCardStatus
        });
        return {
          success: true,
          sellCardSuccess: rechargeRecord.sellCardStatus === 'SUCCESS',
          message: '订单已处理过售卡',
          telegramSent: false
        };
      }

      // 3. 从userId字段获取玩家UID
      const playerUid = rechargeRecord.userId.toString();
      const amount = parseFloat(rechargeRecord.amount.toString());

      Logger.info('开始执行售卡流程', {
        orderId,
        playerUid,
        amount
      });

      // 4. 执行售卡
      const sellResult = await cardSellService.executeCardSell(rechargeRecord.userId, amount);

      // 5. 更新充值记录中的售卡信息
      const updateData: any = {
        playerUid: playerUid,
        cardCoins: sellResult.coins,
        cardProductId: sellResult.productId,
        sellCardStatus: sellResult.success ? 'SUCCESS' : 'FAILED',
        sellCardResponse: JSON.stringify({
          sellResult,
          timestamp: new Date().toISOString()
        }),
        playerNickname: sellResult.nickname,
        updatedAt: new Date()
      };

      await prisma.rechargeRecord.update({
        where: { orderId },
        data: updateData
      });

      // 6. 准备Telegram通知数据
      const telegramData: CardSellNotificationData = {
        orderId,
        amount,
        userId: rechargeRecord.userId,
        playerUid: playerUid,
        coins: sellResult.coins,
        productId: sellResult.productId,
        sellCardSuccess: sellResult.success,
        playerNickname: sellResult.nickname,
        errorMessage: sellResult.errorMessage,
        timestamp: new Date(),
        merchantId: process.env.TELEGRAM_MERCHANT_ID || 'DL79175852939219'
      };

      // 7. 发送Telegram通知
      const telegramSent = await telegramService.sendCardSellNotification(telegramData);

      Logger.info('售卡流程执行完成', {
        orderId,
        playerUid,
        sellCardSuccess: sellResult.success,
        coins: sellResult.coins,
        productId: sellResult.productId,
        telegramSent,
        errorMessage: sellResult.errorMessage
      });

      return {
        success: true,
        sellCardSuccess: sellResult.success,
        message: sellResult.success
          ? `自动售卡成功，玩家${playerUid}已收到${sellResult.coins}M金币`
          : `自动售卡失败：${sellResult.errorMessage}`,
        telegramSent
      };

    } catch (error) {
      Logger.error('执行售卡流程异常', error, { orderId });

      // 发生异常时也要更新状态为FAILED
      try {
        await prisma.rechargeRecord.update({
          where: { orderId },
          data: {
            sellCardStatus: 'FAILED',
            sellCardResponse: JSON.stringify({
              error: error instanceof Error ? error.message : '未知错误',
              timestamp: new Date().toISOString()
            }),
            updatedAt: new Date()
          }
        });
      } catch (updateError) {
        Logger.error('更新售卡失败状态异常', updateError, { orderId });
      }

      return {
        success: false,
        sellCardSuccess: false,
        message: `售卡流程异常：${error instanceof Error ? error.message : '未知错误'}`,
        telegramSent: false
      };
    }
  }

  /**
   * 获取用户充值统计
   */
  async getUserRechargeStats(userId: number) {
    try {
      const [totalAmount, totalCount, completedAmount, completedCount] = await Promise.all([
        prisma.rechargeRecord.aggregate({
          where: { userId },
          _sum: { amount: true },
        }),
        prisma.rechargeRecord.count({
          where: { userId },
        }),
        prisma.rechargeRecord.aggregate({
          where: { userId, status: RechargeStatus.COMPLETED },
          _sum: { amount: true },
        }),
        prisma.rechargeRecord.count({
          where: { userId, status: RechargeStatus.COMPLETED },
        }),
      ]);

      return {
        totalAmount: totalAmount._sum.amount || 0,
        totalCount,
        completedAmount: completedAmount._sum.amount || 0,
        completedCount,
      };
    } catch (error) {
      throw new Error(`获取用户充值统计失败: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }
}

export const rechargeService = new RechargeService();
